// 注册
const User = require('../../../control/User/User')
const tools = require('../../../tools/public');
/**
 * @api {post} /user/register 1.注册
 * @apiGroup User
 *
 * @apiParam {String} Account 账号
 * @apiParam {String} [PassWord] 密码 (密码和验证码必须传一种)
 * @apiParam {Number} [Code] 验证码
 * @apiParamExample {json} Request-Example
 * {
 *  "Account": "15892023484",
 *  "PassWord": "14654654654651465465465465",
 *  "Code": "565896"
 * }
 *
 * @apiSuccessExample  {json} Response-Example
 * {
 *   "code": 200,
 *   "msg": "注册！"
 * }
 */
module.exports = async function (req, res, next) {
    let {Account, PassWord, Code} = req.body,
        result = null,
        Token = tools.create_token();
    try {
        // 账号  + （密码/验证码）参数限制
        if (!Account || (!PassWord && !Code)) return res.send(tools.ReturnData(204, '参数错误,请认真阅读接口文档！'));
        result = await User.Sel_singleArg({Account});
        if (result.length > 0) { // 存在，直接登录
            // 取客户端ip
            let ip = req.ip.match(/\d+\.\d+\.\d+\.\d+/) || null;
            // 拿到登陆过的设备列表
            let deviceList = result[0].LoginIp;
            // 只保留了最多三个设备登录
            if (deviceList.length >= 3) deviceList.shift()
            deviceList.push({ip, Token})
            // 插入数据库
            await User.Upd(result[0]._id, {LoginIp: deviceList});
            res.send(tools.ReturnData(200, '登录成功！', {Token}));
        } else { // 不存在直接注册
            result = await User.Add({Account, PassWord, Code});
            res.send(tools.ReturnData(200, '注册成功！', {Token}));
        }
    } catch (e) {
        console.log(e)
        return res.send(tools.ReturnData(500, '系统内部错误！'));
    }
};